<?php

namespace app\common\job;

use PhpMqtt\Client\Exceptions\MqttClientException;
use think\Exception;
use think\Log;
use think\queue\Job;
use app\common\library\queuemqtt\QueueMqttPublisher;

/**
 * 队列重新发布消息类
 * Class MqttRepublish
 * @package app\common\job
 */
class MqttRepublish
{
    /**
     * 重新发布消息
     * @param Job $job
     * @param $data
     * @throws MqttClientException
     */
    public function republish(Job $job, $data)
    {
        if ($job->attempts() > 3) {
            $job->delete();
            return;
        }
        $logConfig=[
            // 日志记录方式，内置 file socket 支持扩展
            'type'  => 'File',
            // 日志保存目录
            'path'  => ROOT_PATH.'log'.DS.'mqtt'.DS,
            // 日志记录级别
            'level' => ['error', 'log', 'debug', 'notice', 'sql'],
        ];
        Log::init($logConfig);
        try {
            $mqtt = new QueueMqttPublisher();
            $mqtt->publishMessage($data['topic'], $data['data']);
            $message = json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
            Log::error("队列重发消息成功,主题：{$data['topic']}，消息内容:{$message} ".PHP_VERSION);
        } catch (Exception|\Exception|MqttClientException $e) {
            Log::error("队列重发消息失败，失败原因：" . $e->getTraceAsString());
            $job->release(3);
            unset($mqtt);
            return;
        }
        unset($mqtt);
        $job->delete();
    }
}